package com.xingdata.jjxc.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.poisearch.PoiSearch.OnPoiSearchListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.xingdata.jjxc.ComEntity;
import com.xingdata.jjxc.Common;
import com.xingdata.jjxc.R;
import com.xingdata.jjxc.RequestCode;
import com.xingdata.jjxc.adapter.PoiListViewAdapter;
import com.xingdata.jjxc.base.BaseActivity;
import com.xingdata.jjxc.enty.NaviHistoryEntity;
import com.xingdata.jjxc.favorites.FavoritesActivity;
import com.xingdata.jjxc.favorites.FavoritesEntity;
import com.xingdata.jjxc.map.navi.IATController;
import com.xingdata.jjxc.record.MyCustomListView;
import com.xingdata.jjxc.record.RecordSQLiteOpenHelper;
import com.xingdata.jjxc.utils.JUtils;
import com.xingdata.jjxc.utils.JsonParser;
import com.xingdata.jjxc.utils.Log;
import com.xingdata.jjxc.utils.SharedPreTools;
import com.xingdata.jjxc.utils.SystemInfo;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.UUID;

/**
 *
 * @Description: TODO(点击搜索目的地_搜索页面)
 * @date 2015-9-9 下午8:36:55 Creater JiangMin
 */
public class NaviSerchActivity extends BaseActivity implements OnClickListener, OnItemClickListener,
		OnPoiSearchListener {

	private static String TAG = "NaviSerchActivity";

	/** 高德兴趣点搜索列表 */
	private ListView poiSearchListView;

	private PoiListViewAdapter poiListViewAdapter;

	/** private ArrayList《NaviHistoryEntity》 historyEntities = new ArrayList<NaviHistoryEntity>(); */
	private ArrayList<NaviHistoryEntity> naviHistoryEntityList = new ArrayList<NaviHistoryEntity>();

	private Bundle mBundle;

	/** 编辑框edittext */
	private EditText serchEditText;

	/** 搜索button*/
	private TextView search_btn;

	private ImageView search_clear;

	private ImageView search_voice;

	private LinearLayout select_point;

	/** 语音控件 */
	private IATController iatController;

	/**private PoiSearch.Query query;[Poi查询条件类]*/
	private PoiSearch.Query query;

	/**private PoiSearch poiSearch;[POI搜索]	 */
	private PoiSearch poiSearch;// POI搜索

	/**poi返回的结果private PoiResult poiResult; */
	private PoiResult poiResult; // 

	/**定义搜索名字private String queryName; */
	private String queryName;

	private LinearLayout search_ll;
	
	/*家+点击设置*/
	/**家+点击设置,点击进入设置*/
	private LinearLayout search_home_ll;
	/**家的位置，点击进入导航 */
	private TextView search_home_location;
	
	/*公司+点击设置*/
	/**公司+点击设置，点击进入设置*/
	private LinearLayout search_company_ll;
	/**公司的位置，点击进入导航 */
	private TextView search_company_location;

	/**收藏夹布局*/
	private LinearLayout search_favorites_ll;
	
	/*搜索记录*/
	/**搜索历史记录*/
	public static final String SEARCH_HISTORY = "search_history";

	/** 清除按钮 */
	private Button btn_clear_record;
	private RecordSQLiteOpenHelper helper = new RecordSQLiteOpenHelper(this);
	private SQLiteDatabase db;
	private BaseAdapter adapter;
	/** 历史搜索记录listview列表 */
	private MyCustomListView search_record_listview;

	/** 把收藏夹、搜索、地图选点（地点、地名、经度、纬度），来自三个不同地方的数据进行统一提取保存 */
	private ComEntity comEntity;

	@Override
	protected int getContentViewId() {
		return R.layout.navi_search;
	}

	@Override
	protected String getTitleText() {
		return "";
	}

	/**搜索记录初始化*/
	private void initSearchRecord() {
		// TODO Auto-generated method stub
		// 修改字体
		Typeface font = Typeface.createFromAsset(getAssets(), JUtils.TypefacePath);
		
		/*搜索历史列表*/
		search_record_listview = (MyCustomListView) findViewById(R.id.search_record_listview);
		search_record_listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				TextView textView = (TextView) view.findViewById(R.id.search_placeName);
				String name = textView.getText().toString();
				serchEditText.setText(name);
				search_btn.performClick();//模拟点击事件
				Toast.makeText(NaviSerchActivity.this, name, Toast.LENGTH_SHORT).show();
			}
		});
		
		/*清除记录按钮*/
		btn_clear_record = (Button) findViewById(R.id.btn_clear_record);
		btn_clear_record.setTypeface(font);
		btn_clear_record.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				deleteData();
				queryData("");
			}
		});

		Intent intent = getIntent();
		String name = intent.getStringExtra("name");
		serchEditText.setText(name);

		// 第一次进入查询所有的历史记录
		queryData("");
	}

	/**
	 * 插入数据
	 */
	private void insertData(String tempName) {
		db = helper.getWritableDatabase();
		db.execSQL("insert into records(name) values('" + tempName + "')");
		db.close();
	}

	/**
	 * 模糊查询数据
	 */
	private void queryData(String tempName) {
		Cursor cursor = helper.getReadableDatabase().rawQuery(
				"select id as _id,name from records where name like '%" + tempName + "%' order by id desc ", null);
		// 创建adapter适配器对象
		adapter = new SimpleCursorAdapter(this, R.layout.search_record_item, cursor, new String[] { "name" },
				new int[] { R.id.search_placeName }, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
		// 设置适配器
		search_record_listview.setAdapter(adapter);
		adapter.notifyDataSetChanged();
	}

	/**
	 * 检查数据库中是否已经有该条记录
	 */
	private boolean hasData(String tempName) {
		Cursor cursor = helper.getReadableDatabase().rawQuery(
				"select id as _id,name from records where name =?", new String[]{tempName});
		//判断是否有下一个
		return cursor.moveToNext();
	}

	/**
	 * 清空数据
	 */
	private void deleteData() {
		db = helper.getWritableDatabase();
		db.execSQL("delete from records");
		db.close();
	}




	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		initView();

		initSearchRecord();
		// initData();
		// testDB();
		comEntity = new ComEntity();
		initTitle();


		// 初始化语音接口
		iatController = new IATController(NaviSerchActivity.this, new RecognizerDialogListener() {
			public void onResult(RecognizerResult results, boolean isLast) {
				if(!isLast)
					printResult(results);
			}

			/**
			 * 识别回调错误.
			 */
			public void onError(SpeechError error) {
				System.out.println(error.getPlainDescription(true));
			}
		});

		if (mBundle != null ) {
			String searchKey = mBundle.getString("voiceresult");
			if(searchKey != null && searchKey.length() > 0 ){
				serchEditText.setText(searchKey);
				doSearchQuery(searchKey);
			}
		}



	}

	// 用HashMap存储听写结果
	private void printResult(RecognizerResult results) {
		HashMap<String, String> mIatResults = new LinkedHashMap<String, String>();
		String[] redundantCharacter = { "到", "往", "去" };

		String text = JsonParser.parseIatResult(results.getResultString());
		JSONObject resultJson = null;
		String sn = null;
		// 读取json结果中的sn字段
		try {
			resultJson = new JSONObject(results.getResultString());
			sn = resultJson.optString("sn");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		mIatResults.put(sn, text);
		final StringBuffer resultBuffer = new StringBuffer();
		for (String key : mIatResults.keySet()) {
			resultBuffer.append(mIatResults.get(key));
		}
		String searchKey = resultBuffer.toString();

		for (int i = 0; i < redundantCharacter.length; i++) {
			int index = resultBuffer.indexOf(redundantCharacter[i]);
			if (index > -1) {
				searchKey = resultBuffer.substring(index+1 );
			}
		}
		if (searchKey.length() != 0 ) {//&& !((Boolean) resultJson.opt("ls"))
			Log.d(TAG, "语音识别：" + searchKey.toString());

			if(searchKey != null && searchKey.length() > 0 ){
				serchEditText.removeTextChangedListener(watcher);
				serchEditText.setText(searchKey);
				serchEditText.addTextChangedListener(watcher);
				doSearchQuery(searchKey);
			}
		}

	}


	private void initTitle() {
		((TextView)findViewById(R.id.navi_title_city)).setText(SystemInfo.City);
		((TextView)findViewById(R.id.navi_weather)).setText(SystemInfo.Weather);
		((TextView)findViewById(R.id.navi_temperature)).setText(SystemInfo.Temperature);
	}

	private void initView() {

		// 修改字体
		Typeface font = Typeface.createFromAsset(getAssets(), JUtils.TypefacePath);

		//bundle

		//String name = getIntent().getStringExtra("name");

		// 家的位置，具体地址，点击进入地图
		search_home_location = (TextView) findViewById(R.id.search_home_location);
		search_home_location.setTypeface(font);
		comEntity = (ComEntity)SharedPreTools.getBean(getApplicationContext(), "homeEntity");
		if (comEntity != null) {
			search_home_location.setText(comEntity.getPlace_name());
		}
//		search_home_location.setText(SharedPreTools.getString(NaviSerchActivity.this, Common.HOME_ADDRESS, null));
		search_home_location.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				Bundle bundle = new Bundle();
				comEntity = (ComEntity)SharedPreTools.getBean(getApplicationContext(), "homeEntity");
				bundle.putSerializable("poi3", comEntity);
				intent.putExtras(bundle);
				setResult(RESULT_OK, intent);
				finish();
			}
		});

		// 公司的位置，具体地址，点击进入地图
		search_company_location = (TextView) findViewById(R.id.search_company_location);
		search_company_location.setTypeface(font);
		ComEntity comEntity2 = (ComEntity)SharedPreTools.getBean(getApplicationContext(), "companyEntity");
		if (comEntity2 != null) {
			search_company_location.setText(comEntity2.getPlace_name());
		}
		search_company_location.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				Bundle bundle = new Bundle();
				comEntity = (ComEntity)SharedPreTools.getBean(getApplicationContext(), "companyEntity");
				bundle.putSerializable("poi3", comEntity);
				intent.putExtras(bundle);
				setResult(RESULT_OK, intent);
				finish();
			}
		});

		search_favorites_ll = (LinearLayout) findViewById(R.id.search_favorites_ll);
		search_favorites_ll.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent = new Intent(NaviSerchActivity.this, FavoritesActivity.class);
				startActivityForResult(intent, RequestCode.REQUESTCODE_FAVORITES);
			}
		});

		((TextView) findViewById(R.id.search_home_tv)).setTypeface(font);
		((TextView) findViewById(R.id.search_home_setting)).setTypeface(font);

		((TextView) findViewById(R.id.search_company_tv)).setTypeface(font);
		((TextView) findViewById(R.id.search_company_setting)).setTypeface(font);

		((TextView) findViewById(R.id.search_favorites_tv)).setTypeface(font);
		((TextView) findViewById(R.id.search_favorites_setting)).setTypeface(font);
		((TextView) findViewById(R.id.historic_record)).setTypeface(font);
		((EditText) findViewById(R.id.search_et)).setTypeface(font);

		search_voice = (ImageView) findViewById(R.id.search_voice);
		search_voice.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (iatController != null) {
					iatController.start();
				}
			}
		});
		search_clear = (ImageView) findViewById(R.id.search_clear);
		search_btn = (TextView) findViewById(R.id.search_btn);
		serchEditText = (EditText) findViewById(R.id.search_et);
		select_point = (LinearLayout) findViewById(R.id.select_point);

		select_point.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				Intent intent = new Intent(NaviSerchActivity.this, MapSelectActivity.class);
				startActivityForResult(intent,RequestCode.REQUESTCODE_COMMON_ADDRESS);
			}
		});

		search_clear.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				serchEditText.setText("");
			}
		});

		search_btn.setOnClickListener(this);

		serchEditText.addTextChangedListener(watcher);

		// 搜索框的键盘搜索键点击回调
		serchEditText.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {// 修改回车键功能
					search_btn.performClick();
					// 先隐藏键盘
					((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
							getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
					String str = serchEditText.getText().toString().trim();
					// 按完搜索键后将当前查询的关键字保存起来,如果该关键字已经存在就不执行保存
					boolean hasData = hasData(serchEditText.getText().toString().trim());
					if (!hasData && !TextUtils.isEmpty(str)) {
						insertData(serchEditText.getText().toString().trim());
						queryData("");
					}
					// TODO 根据输入的内容模糊查询商品，并跳转到另一个界面，由你自己去实现
//					Toast.makeText(NaviSerchActivity.this, "clicked!", Toast.LENGTH_SHORT).show();

				}
				return false;
			}
		});

		search_ll = (LinearLayout) findViewById(R.id.search_ll);

		search_home_ll = (LinearLayout) findViewById(R.id.search_home_ll);
		search_home_ll.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(NaviSerchActivity.this, HomeCompanySetActivity.class);
				startActivityForResult(intent, RequestCode.REQUESTCODE_HOMESETTING);
			}
		});

		search_company_ll = (LinearLayout) findViewById(R.id.search_company_ll);
		search_company_ll.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent companyIntent = new Intent(NaviSerchActivity.this, HomeCompanySetActivity.class);
				startActivityForResult(companyIntent, RequestCode.REQUESTCODE_COMMPANYSETTING);
			}
		});

		// 判断，是语音搜索intent进来后，显示搜索框listview
		if(mBundle != null){
			String str = mBundle.getString("setVisible");
			if (str != null && str.equals("visible")) {
				Log.d(TAG, "显示 搜索框结果listview");
				search_ll.setVisibility(View.GONE);
				poiSearchListView.setVisibility(View.VISIBLE);
			}
		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		if (iatController != null) {
			iatController.onDestory();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		// 设置家地址返回结果
		case RequestCode.REQUESTCODE_HOMESETTING:
			if (resultCode==RESULT_OK) {
				// 从地图选点，设置家的地址
				ComEntity comEntity1 = (ComEntity) data.getSerializableExtra(Common.MAPSELECT_PLACENAME_FROMEHOMECOMPANYACT);
				 if (comEntity1 !=null) {
					 Log.d(TAG, "1");
					 search_home_location.setText(comEntity1.getPlace_name());

					 SharedPreTools.putBean(getApplicationContext(), "homeEntity", comEntity1);
				}
				// 从收藏夹选择，设置家的地址
				FavoritesEntity favoritesEntity = (FavoritesEntity) data.getSerializableExtra(Common.PLACE_NAME_MIDDLE);
				if (favoritesEntity != null) {
					Log.d(TAG, "2");
					String placeNameFromFavorites = favoritesEntity.getPlace_name();
					search_home_location.setText(placeNameFromFavorites);

					ComEntity comEntity = new ComEntity();
					comEntity.setPlace_name(favoritesEntity.getPlace_name());
					comEntity.setPlace_address(favoritesEntity.getPlace_address());
					comEntity.setPlace_lng(favoritesEntity.getPlace_lng());
					comEntity.setPlace_lat(favoritesEntity.getPlace_lat());

					SharedPreTools.putBean(getApplicationContext(), "homeEntity", comEntity);

				}

				// 在下一个界面HomeCompanySetActivity搜索，设置家的地址
				NaviHistoryEntity naviHistoryEntity = (NaviHistoryEntity) data.getSerializableExtra("homeOrcompany");
				if (naviHistoryEntity != null) {
					Log.d(TAG, "3");
					String placeNameFromSearch = naviHistoryEntity.getloca_nickname();
					if (placeNameFromSearch != null) {
						search_home_location.setText(placeNameFromSearch);

						ComEntity comEntity = new ComEntity();
						comEntity.setPlace_name(naviHistoryEntity.getloca_nickname());
						comEntity.setPlace_address(naviHistoryEntity.getloca_address());
						comEntity.setPlace_lng(naviHistoryEntity.getloca_lng());
						comEntity.setPlace_lat(naviHistoryEntity.getloca_lat());

						SharedPreTools.putBean(getApplicationContext(), "homeEntity", comEntity);

					}
				}

				queryData("");// 设置家位置，搜索的时候，保存搜索记录

			}
			break;

		// 设置公司地址返回结果
		case RequestCode.REQUESTCODE_COMMPANYSETTING:
			if (resultCode==RESULT_OK) {
				// 从地图选点，设置公司的地址
				// 从地图选点，设置家的地址
				ComEntity comEntity1 = (ComEntity) data.getSerializableExtra(Common.MAPSELECT_PLACENAME_FROMEHOMECOMPANYACT);
				 if (comEntity1 !=null) {
					 search_company_location.setText(comEntity1.getPlace_name());

					 SharedPreTools.putBean(getApplicationContext(), "companyEntity", comEntity1);
				}
				// 从收藏夹选择，设置公司的地址
				FavoritesEntity favoritesEntity = (FavoritesEntity) data.getSerializableExtra(Common.PLACE_NAME_MIDDLE);
				if (favoritesEntity != null) {
					String placeNameFromFavorites = favoritesEntity.getPlace_name();
					search_company_location.setText(placeNameFromFavorites);

					ComEntity comEntity = new ComEntity();
					comEntity.setPlace_name(favoritesEntity.getPlace_name());
					comEntity.setPlace_address(favoritesEntity.getPlace_address());
					comEntity.setPlace_lng(favoritesEntity.getPlace_lng());
					comEntity.setPlace_lat(favoritesEntity.getPlace_lat());

					SharedPreTools.putBean(getApplicationContext(), "companyEntity", comEntity);
				}

				// 在下一个界面HomeCompanySetActivity搜索，设置公司的地址
				NaviHistoryEntity naviHistoryEntity = (NaviHistoryEntity) data.getSerializableExtra("homeOrcompany");
				if (naviHistoryEntity != null) {
					String placeNameFromSearch = naviHistoryEntity.getloca_nickname();
					if (placeNameFromSearch != null) {
						search_company_location.setText(placeNameFromSearch);

						ComEntity comEntity = new ComEntity();
						comEntity.setPlace_name(naviHistoryEntity.getloca_nickname());
						comEntity.setPlace_address(naviHistoryEntity.getloca_address());
						comEntity.setPlace_lng(naviHistoryEntity.getloca_lng());
						comEntity.setPlace_lat(naviHistoryEntity.getloca_lat());

						SharedPreTools.putBean(getApplicationContext(), "companyEntity", comEntity);
					}
				}

				queryData("");// 设置公司位置，搜索的时候，保存搜索记录

			}
			break;

		// 获取收藏界面实体结果，然后传递到导航的地图界面
		case RequestCode.REQUESTCODE_FAVORITES:
			if (resultCode==RESULT_OK) {
				if (data != null) {

					Bundle bundle = data.getExtras();
					if (bundle != null) {
						FavoritesEntity favoritesEntity = (FavoritesEntity) bundle.getSerializable(Common.FAVORITES_POI);

						Intent intent = new Intent();
						Bundle bundle2 = new Bundle();
						bundle2.putSerializable("poi2", favoritesEntity);
						intent.putExtras(bundle2);
						setResult(RESULT_OK, intent);
					}
				}
				finish();
			}

		break;
		case RequestCode.REQUESTCODE_COMMON_ADDRESS:{
			if (resultCode==RESULT_OK) {
				if (data != null) {

					Bundle bundle = data.getExtras();
					if (bundle != null) {
						ComEntity comEntity = (ComEntity)bundle.getSerializable(Common.MAPSELECT_PLACENAME);


						Intent intent = new Intent();
						Bundle bundle2 = new Bundle();
						bundle2.putSerializable("poi", comEntity);
						intent.putExtras(bundle2);
						setResult(RESULT_OK, intent);
					}
				}
				finish();
			}
		}
		break;
		default:
			break;
		}
	}

	/**
	 * ysc20160826 监听地址编辑框是否有文字输入变化
	 */
	private TextWatcher watcher = new TextWatcher() {

		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
			// TODO Auto-generated method stub
			if (s.length() == 0) {
				search_voice.setVisibility(View.VISIBLE);
				search_clear.setVisibility(View.GONE);
				search_btn.setVisibility(View.GONE);
			} else {
				search_voice.setVisibility(View.GONE);
				search_clear.setVisibility(View.VISIBLE);
				search_btn.setVisibility(View.VISIBLE);
			}

		}

		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
			String tempName = serchEditText.getText().toString();
			// 根据tempName去模糊查询数据库中有没有数据
			queryData(tempName);
		}

	};

	// private void initData() {
	// try {
	// if (historyEntities.size() == 0) {
	// historyEntities.addAll(NaviHistoryEntityOpertate.getInstance()
	// .seletAllHistory(
	// SystemInfo.GetDatabaseHelperInstance(this)));
	// }
	// adapter.notifyDataSetChanged();
	// } catch (Exception e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	// }

	private boolean isAddPoint = false;
	@Override
	protected void initViews() {
		isAddPoint = false;
		((ImageView) findViewById(R.id.title_back)).setOnClickListener(this);
		mBundle = getIntent().getExtras();
		if (mBundle != null ) {
			String str = mBundle.getString("waypoint");
			if(str != null && str.equals("addpoint")){
				isAddPoint = true;
			}else {
//				naviHistoryEntityList.addAll((Collection<? extends NaviHistoryEntity>) mBundle.getParcelableArrayList("poi"));
			}
		}
		poiSearchListView = (ListView) findViewById(R.id.poiSearchListView);
		poiListViewAdapter = new PoiListViewAdapter(naviHistoryEntityList, this);
		poiSearchListView.setAdapter(poiListViewAdapter);
		poiSearchListView.setOnItemClickListener(this);


	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_back:
			finish();
			break;

		case R.id.search_btn:
			String strSerach = serchEditText.getText().toString().trim();
			if (strSerach.length() == 0) {
				showToast("搜索框内容不能为空！");
				return;
			}
			doSearchQuery(strSerach);
			search_record_listview.setVisibility(View.GONE);
			// 实现输入框有文字的时候，所谓的界面跳转，不过是隐藏了一些布局而已
			search_ll.setVisibility(View.GONE);
			poiSearchListView.setVisibility(View.VISIBLE);
			// 先判断搜索字符串是否已经保存，字符串不为空，然后就保存为历史搜索记录
			boolean hasData = hasData(serchEditText.getText().toString().trim());
			if (!hasData && !TextUtils.isEmpty(strSerach)) {
				insertData(serchEditText.getText().toString().trim());
				queryData("");
			}
			break;

		default:
			break;
		}
	}


	/** 弹出搜索页面listView的点击事件 */
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
		NaviHistoryEntity naviHistoryEntity = naviHistoryEntityList.get(position);
		
		/*是否有用户id，如果有，就保存UserEntity的id到NaviHistoryEntity的id里面*/
		if (SystemInfo.getUserInfo() != null) {
			naviHistoryEntity.setuser_id(SystemInfo.getUserInfo().getUserid());
		}

		naviHistoryEntity.setloca_id(UUID.randomUUID().toString());

		naviHistoryEntity.setcreate_time(System.currentTimeMillis() + "");
		// NaviHistoryEntityOpertate.getInstance().addHistory(
		// SystemInfo.GetDatabaseHelperInstance(this), historyEntity);
		if(isAddPoint){
			AddWayPointsActivity.wayPointArrayList.add(naviHistoryEntity);
		}
		Intent resultIntent = new Intent();
		Bundle bundle = new Bundle();
		ComEntity comEntity = new ComEntity();
		NaviHistoryEntity naviEnity = naviHistoryEntityList.get(position);
		if(null != naviEnity){
			comEntity.setPlace_name(naviEnity.getloca_nickname());
			comEntity.setPlace_address(naviEnity.getloca_address());
			comEntity.setPlace_lng(naviEnity.getloca_lng());
			comEntity.setPlace_lat(naviEnity.getloca_lat());
			bundle.putSerializable("poi",comEntity );
			resultIntent.putExtras(bundle);

			setResult(RESULT_OK, resultIntent);
		}else{
			setResult(RESULT_CANCELED, resultIntent);
		}

		finish();
	}

	/**
	 * 开始进行poi搜索
	 */
	protected void doSearchQuery(String reslut) {
		queryName = reslut;

		int currentPage = 0;
		query = new PoiSearch.Query(reslut, "", SystemInfo.City);// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
		query.setPageSize(10);// 设置每页最多返回多少条poiitem，在listview最多显示10条相关搜索结果信息
		query.setPageNum(currentPage);// 设置查第一页
		poiSearch = new PoiSearch(this, query);
		/*poiSearch监听*/
		poiSearch.setOnPoiSearchListener(this);
		poiSearch.searchPOIAsyn();

	}

	/*poiSearch监听*/
	@Override
	public void onPoiSearched(PoiResult result, int rCode) {
		if (rCode == 0) {
			Log.i(TAG, "POI搜索成功");
			if (result != null && result.getQuery() != null) {// 搜索poi的结果
				if (result.getQuery().equals(query)) {// 是否是同一条
					poiResult = result;
					// 取得搜索到的poiitems有多少页
					List<PoiItem> poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
					List<SuggestionCity> suggestionCities = poiResult.getSearchSuggestionCitys();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息

					if (poiItems != null && poiItems.size() > 0) {

						naviHistoryEntityList.clear();

						PoiItem poiItem = null;

						NaviHistoryEntity naviHistoryEntity = null;

						for (int i = 0; i < poiItems.size(); i++) {

							poiItem = poiItems.get(i);

							naviHistoryEntity = new NaviHistoryEntity();

							naviHistoryEntity.setloca_id(UUID.randomUUID().toString());

							naviHistoryEntity.setloca_nickname(poiItem.getTitle());
							naviHistoryEntity.setloca_address(poiItem.getSnippet());
							Log.d(TAG, "地名setloca_nickname="+poiItem.getTitle());
							Log.d(TAG, "地址setloca_address="+poiItem.getSnippet());

							naviHistoryEntity.setloca_lng(poiItem.getLatLonPoint().getLongitude() + "");
							naviHistoryEntity.setloca_lat(poiItem.getLatLonPoint().getLatitude() + "");
							Log.d(TAG, "经度setloca_lng="+poiItem.getLatLonPoint().getLongitude());
							Log.d(TAG, "纬度setloca_lat="+poiItem.getLatLonPoint().getLatitude());

							naviHistoryEntity.setloca_areaid(poiItem.getProvinceCode());
							naviHistoryEntityList.add(naviHistoryEntity);
							poiListViewAdapter.notifyDataSetChanged();
						}
					} else if (suggestionCities != null && suggestionCities.size() > 0) {
						// showSuggestCity(suggestionCities);
						showToast("这里没有搜索到结果推荐...");
					} else {
						showToast(getResources().getString(R.string.no_result).toString());
					}
				}
			} else {
				showToast(getResources().getString(R.string.no_result).toString());
			}
		} else if (rCode == 27) {
			showToast(getResources().getString(R.string.error_network).toString());
		} else if (rCode == 32) {
			showToast(getResources().getString(R.string.error_key).toString());
		} else {
			showToast(getResources().getString(R.string.error_other).toString());
		}

	}



}
